package com.ly.mpayment.core.util;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.JsonObject;
import com.ly.mpayment.core.secuity.MD5;

public class TokenUtils {
	public static final String TOKEN_KEY_NUM = "_TOKEN_NUM";
	private static String privatekey = "-----BEGIN PRIVATE KEY-----MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4ZtdaIrd1BPIJtfnF0TjIK5inQAXZ3XlCrUlJdP+XHwIRxdv1FsN12XyMYO/6ymLmo9ryoQeIrsXBXYqlET3zfAY+diwCb0HEsVvhisthwMU4gZQu6TYW2s9LnXZB5rVtcBK69hcSlA2kZudMZWxZcj0L7KMfO2rIvaHw/qaVOE9j0T257Z8Kp2CLF9MUgX0ObhIsdumFRLaLDvDUmBPr2zuh/34j2XmWwn1yjN/WvGtdfhXW79Ki1S40HcWnygHgLV8sESFKUxxQmKvPUTwDOIwLFL5WtE8Mz7N++kgmDcmWMCHc8kcOIu73Ta/3D4imW7VbKgHZo9+K3ESFE3RjAgMBAAECggEBAJTEIyjMqUT24G2FKiS1TiHvShBkTlQdoR5xvpZMlYbNtVWxUmrAGqCQ/TIjYnfpnzCDMLhdwT48Ab6mQJw69MfiXwc1PvwX1e9hRscGul36ryGPKIVQEBsQG/zc4/L2tZe8ut+qeaK7XuYrPp8bk/X1e9qK5m7j+JpKosNSLgJjNIbYsBkG2Mlq671irKYj2hVZeaBQmWmZxK4fw0Istz2WfN5nUKUeJhTwpR+JLUg4ELYYoB7EO0Cej9UBG30hbgu4RyXA+VbptJ+H042K5QJROUbtnLWuuWosZ5ATldwOu03dIXL0SH0ao5NcWBzxU4F2sBXZRGP2x/jiSLHcqoECgYEA4qD7mXQpu1b8XO8U6abpKloJCatSAHzjgdR2eRDRx5PMvloip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2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT69s7of9+I9l5lsJ9cozf1rxrXX4V1u/SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8AziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0YwIDAQAB-----END PUBLIC KEY-----";
	private static String key = "7389ab939fdc349f64b9df1884f4dc1c";

	/**
	 * 生成token值
	 * 
	 * @param req
	 * @return
	 */
	public static String createToken(String phone, String password, String dateStr) {
		return MD5.md5(phone.concat(password).concat(dateStr));
	}

	public static void main(String[] args) {
		// Map<String, String> map = new HashMap<>();
		// for (int i = 0; i < 10001; i++) {
		// String temp = MD5.md5("".concat("123456").concat(new
		// Date().toString()));
		// map.put(temp, temp);
		// }
		// System.out.println(map.size());
		String token = createToken("sadsssssssssseeeeeeeeeeeeess", "2017-02-02 02:12:22");
		System.out.println(token);
		DecodedJWT jwt = JWT.decode(token + "dllllllll");
		System.out.println(jwt.getSubject());
	}

	// final RSAPrivateKey privateKey = null;//Get the key instance
	final static String privateKeyId = privatekey;// Create an Id for the above
													// key

	public static String createToken(String userid, String time) {
		Algorithm algorithm;
		try {
			algorithm = Algorithm.HMAC256(key);
			JsonObject json = new JsonObject();
			json.addProperty(Config.tokenSignAttr, userid);
			json.addProperty(Config.tokenSignTime, time);
			return JWT.create().withSubject(json.toString()).sign(algorithm);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	public static boolean verifyToken(String token) {
		Algorithm algorithm;
		try {
			algorithm = Algorithm.HMAC256(key);
			JWTVerifier verifier = JWT.require(algorithm).withIssuer("auth0").build();
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 验证token是否正确
	 * 
	 * @param req
	 * @return
	 */
	public static boolean authTokenIsOk(HttpServletRequest req, String tokenKey, String token) {

		if (StringUtils.isBlank(token)) {
			return false;
		}

		HttpSession session = req.getSession();
		String sessionToken = (String) session.getAttribute(tokenKey);
		if (StringUtils.equals(sessionToken, token)) {
			return true;
		}
		return false;
	}

	/**
	 * 验证token是否正确
	 * 
	 * @param req
	 * @return
	 */
	public static boolean authTokenNumIsOk(HttpServletRequest req, String tokenKey, String token) {

		if (StringUtils.isBlank(token)) {
			return false;
		}
		HttpSession session = req.getSession();
		// 记录下验证的次数
		Integer num = (Integer) session.getAttribute(tokenKey + TOKEN_KEY_NUM);
		if (num < 5) {
			session.setAttribute(tokenKey + TOKEN_KEY_NUM, num + 1);
			return true;
		}
		return false;
	}
}
